﻿using God.ShoppingWebApi.Entities;
using God.ShoppingWebApi.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using IdentityModel.Client;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;
using Volo.Abp.Application.Services;
using God.ShoppingWebApi.DTO.User;

namespace God.ShoppingWebApi.Service
{
    public class AdminLoginService : ApplicationService, IAdminLoginService
    {
        private readonly IConfiguration _configuration;
        public AdminLoginService(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        [HttpPost]
        public async Task<string> GetUserTokenAsync(UserLoginDTO login)
        {
            var client = new HttpClient();//定义http客户端
            var disco = await client.GetDiscoveryDocumentAsync(_configuration["AuthServer:Authority"]);
            var s = _configuration["AuthServer:AppSecret"];
            var tokenClient = new TokenClient(client, new TokenClientOptions
            {
                Address = disco.TokenEndpoint,//访问Ids4的令牌地址
                ClientId = _configuration["AuthServer:AppId"],//clientId
                ClientSecret = _configuration["AuthServer:AppSecret"]//clientSecret
            });
            var tokenResponse = await tokenClient.RequestPasswordTokenAsync(login.UserInfoName, login.UserPassword, "ShoppingWebApi");
            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return string.Empty;
            }
            return tokenResponse.Json.ToString();
        }
    }
}
